/**
 * Created by zhanglihe on 16/1/23.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog'
], function ($, common, ready, Collection, template, Model, dialog) {

    var id = getUrlPath(3);

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },
        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'custom_category_goodss?id=' + id,
                model: {
                    url: {
                        delete: _global.url.api + 'custom_category_goods'
                    },
                    event: {
                        '.item-remove': 'remove'
                    },
                    remove: function (e) {
                        e.preventDefault();
                        var item_id = this.get_data('id');
                        dialog({
                            content: '确定要删除吗?',
                            ok: function () {
                                $.ajax({
                                    url: _global.url.api + 'custom_category_goods',
                                    type: 'delete',
                                    async: false,
                                    data: {id: item_id},
                                    success: function (res) {
                                        if (res.code == 0) {
                                            _this.collection.reload();
                                        } else {
                                            Alert({msg: res.msg, type: 'error'});
                                        }
                                    }, error: function () {
                                        Alert({msg: '通讯错误', type: 'error'});
                                    }
                                });
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    }
                },
                callback: function () {
                    loaded();//移除加载效果
                }
            });
            this.collection.fetch();
        },
        event: function () {
            var _this = this;

            $("body").on("click", '#btn-goods-search', function (e) {
                e.preventDefault();
                _this.select_goods(e);
            });

            $('#btn-add').on('click', function (e) {
                e.preventDefault();
                dialog({
                    title: '增加商品',
                    width: '888',
                    content: template('add-tpl'),
                    ok: function () {
                        var goods_id = goods_ids = '';
                        $(".goods_id").each(function () {
                            if ($(this).val()) {
                                goods_id = $(this).val();
                                goods_ids = (goods_ids ? goods_ids + ',' : '') + goods_id
                            }
                        });
                        if (goods_ids == '') {
                            Alert({msg: '请选择要商品', type: 'error'});
                            return false;
                        }
                        var data = {
                            goods_ids: goods_ids,
                            id: id
                        };
                        if (new Model({
                                url: _global.url.api + 'custom_category_goods',
                                data: data
                            }).post()) {
                            _this.collection.reload();
                            return true;
                        } else {
                            return false;
                        }
                    }, cancel: function () {
                    }
                }).show();
            });
        },
        select_goods: function (e) {
            var goods_collection = new Collection({
                container: 'data-goods-list',
                template: 'data-goods-items',
                page_dom: 'pagination-goods',
                url: _global.url.api + 'promotion_goods_search',
                condition: {keyword: $("#keyword").val(), limit: 3},
                model: {
                    event: {
                        '.item-bind:click': 'addgoods',
                        '.show-online:click': 'setshow'
                    },
                    addgoods: function (e) {
                        e.preventDefault();
                        var id = this.data.id;
                        var vals = new Array();
                        $(".goods_id").each(function () {
                            if ($(this).val()) {
                                vals.push($(this).val());
                            }
                        });
                        /*if (vals.length > 0) {
                         $('.goods-item-del').click();//只能选择一个商品（特别增加代码）
                         }*/
                        var goods_id = ',' + vals.join(",") + ',';
                        if (goods_id.indexOf(',' + id + ',') != -1) {
                            Alert({msg: '请不要重复添加同一商品', type: 'error'});
                            return false;
                        }
                        $('#goods-item').append(template('goods-item-tpl', {
                            goods_id: this.data.id,
                            goods_name: this.data.name,
                            price: this.data.price
                        }));
                        $("#div_goods").show();
                        $('.goods-item-del').on('click', function (e) {
                            e.preventDefault();
                            var idTmp = $(this).parent().parent().find('[name=goods_id]').val();
                            $(this).parent().parent().remove();
                            $('.item-bind' + idTmp).html('选择').removeClass('btn-success').addClass('btn-default');
                        });
                        $('.item-bind' + id).html('已选择').removeClass('btn-default').addClass('btn-success');
                    }

                },
                callback: function () {
                    loaded();
                    var vals = new Array();
                    $(".goods_id").each(function () {
                        if ($(this).val()) {
                            vals.push($(this).val());
                        }
                    });
                    if (vals.length > 0) {
                        var goods_id = ',' + vals.join(",") + ',';
                        var data = goods_collection.result.data;
                        for (var i = 0; i < data.length; i++) {
                            var tmpId = data[i].id;
                            if (goods_id.indexOf(',' + tmpId + ',') != -1) {
                                $('.item-bind' + tmpId).html('已选择').removeClass('btn-default').addClass('btn-success');
                            }
                        }
                    }
                }
            });
            goods_collection.fetch();
        }
    };
    new index();
});